package com.kiss.fw.action;

import org.apache.log4j.Logger;

import com.kiss.fw.context.ActionContext;
import com.kiss.fw.exceptions.ActionException;
import com.kiss.fw.utils.Constants;
import com.kiss.fw.utils.Util;

public abstract class AbstractAction {
	/**
	 * Responsible for validating the request.
	 * 
	 * @param ActionContext _context
	 * @return boolean
	 */
	public abstract boolean validate(ActionContext _context);
	
	/**
	 * Execute the action.
	 * 
	 * @param ActionContext _context
	 * @throws ActionException
	 */
	public void execute(ActionContext _context) throws ActionException {
		if(_context.isAction(Constants.Mappings.CREATE_ACTION)) {
			create(_context);
		}
		else if(_context.isAction(Constants.Mappings.READ_ACTION)) {
			read(_context);
		}
		else if(_context.isAction(Constants.Mappings.UPDATE_ACTION)) {
			update(_context);
		}
		else if(_context.isAction(Constants.Mappings.DELETE_ACTION)) {
			delete(_context);
		}
		else if(_context.isAction(Constants.Mappings.SEARCH_ACTION)) {
			search(_context);
		}
		else if(_context.isAction(Constants.Mappings.BROWSE_ACTION)) {
			browse(_context);
		}
	}
	
	public abstract void create(ActionContext _context) throws ActionException;
	public abstract void read(ActionContext _context) throws ActionException;
	public abstract void update(ActionContext _context) throws ActionException;
	public abstract void delete(ActionContext _context) throws ActionException;
	public abstract void search(ActionContext _context) throws ActionException;
	public abstract void browse(ActionContext _context) throws ActionException;
	
	protected static boolean isValidInput(final String _input, final String _validInputProperty) {
		boolean returnVal = false;
		
		if(!Util.containsSpecialCharacters(_input)) {
			returnVal = Util.containsToken(Util.getProperty(_validInputProperty), ",", _input, true);
		}
		
		return returnVal;
	}
	
	protected static void handleActionException(final Logger _logger, final String _message, Exception _exception) throws ActionException {
		Util.handleException(_logger, _message, _exception);
		
		if(_exception instanceof ActionException) {
			throw (ActionException)_exception;
		}
		else {
			throw Constants.Exceptions.ACTION_EXCEPTION;
		}
	}
}